<template>
  <div class="mindray-system">
    <!-- 第一层：顶部导航栏 -->
    <header class="top-navigation" :class="{ 'scrolled': isScrolled }">
      <!-- Mindray Logo -->
      <div class="logo-container">
        <img src="/v2_soxp5q.png" alt="Mindray" class="mindray-logo" />
        </div>
      
      <!-- 导航菜单 -->
      <nav class="nav-menu">
        <a href="#" class="nav-item">产品及解决方案</a>
        <a href="#" class="nav-item">医疗创新</a>
        <a href="#" class="nav-item">用户服务</a>
        <a href="#" class="nav-item">投资者关系</a>
        <a href="#" class="nav-item">人才招聘</a>
        <a href="#" class="nav-item">关于我们</a>
      </nav>
      
      <!-- 登录注册区域 -->
      <div class="auth-container">
        <div v-if="!isLoggedIn" class="auth-buttons">
          <button class="auth-btn login-btn" @click="showLoginDialog">登录</button>
          <button class="auth-btn register-btn" @click="showRegisterDialog">注册</button>
        </div>
        <div v-else class="logged-in-section">
          <button class="console-btn" @click="goToConsole">控制台</button>
          <el-dropdown @command="handleUserCommand">
            <span class="user-name">
              {{ currentUser?.realName || currentUser?.username }}
              <el-icon><ArrowDown /></el-icon>
              </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                <el-dropdown-item command="settings">设置</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </header>

    <!-- 展示图片区域 -->
    <div class="hero-banner">
      <img src="/icons/guide-video-kv-pc.jpg" alt="迈瑞设备操作视频" class="hero-image" />
      <div class="hero-overlay">
        <h1 class="hero-title">迈瑞医疗设备模拟操作平台</h1>
        <!-- <p class="hero-subtitle">专业医疗设备模拟操作平台</p> -->
      </div>
    </div>

    <!-- 第二层：搜索栏和设备分类 -->
    <div class="search-categories-container">
      <!-- 搜索栏 -->
      <div class="search-container">
        <div class="search-wrapper">
          <input 
              v-model="searchKeyword"
            type="text" 
            placeholder="请输入搜索内容" 
            class="search-input"
            @keyup.enter="handleSearch"
          />
          <button class="search-button" @click="handleSearch">
                <el-icon><Search /></el-icon>
          </button>
          </div>
        </div>

      <!-- 设备分类按钮 -->
      <div class="device-categories">
        <div
          v-for="category in deviceCategories"
          :key="category.id"
          class="category-item"
          :class="{ active: selectedCategory === category.id }"
          @click="selectCategory(category.id)"
        >
          <div class="category-icon">
            <img :src="category.iconPath" :alt="category.name" />
              </div>
          <div class="category-name">{{ category.name }}</div>
            </div>
              </div>
            </div>

    <!-- 第三层：设备管理按钮 -->
    <div class="management-container">
      <div class="management-buttons">
        <button v-if="!isEditingImages" class="mgmt-btn add-btn" @click="showAddDeviceDialog">
          <el-icon><Plus /></el-icon>
          新增设备
        </button>
        <button v-if="!isEditingImages" class="mgmt-btn edit-info-btn" @click="editDeviceInfo" :disabled="!canEditDeviceInfo">
          <el-icon><Edit /></el-icon>
          编辑设备信息
        </button>
        <button v-if="!isEditingImages" class="mgmt-btn delete-btn" @click="deleteSelectedDevice" :disabled="isDeleteDisabled">
          <el-icon><Delete /></el-icon>
          删除设备
        </button>
        <button v-if="!isEditingImages" class="mgmt-btn edit-btn" @click="editSelectedDevice" :disabled="!canEditDeviceImages">
          <el-icon><Picture /></el-icon>
          编辑设备界面
        </button>
        
        <!-- 图片编辑模式按钮 -->
        <div v-if="isEditingImages" class="edit-mode-buttons">
          <span class="edit-mode-title">界面编辑模式 - {{ selectedDevice?.name }}</span>
          <button class="mgmt-btn import-btn" @click="importCoordinates">
            <el-icon><Upload /></el-icon>
            导入
          </button>
          <button class="mgmt-btn exit-btn" @click="exitImageEditMode">
            <el-icon><Check /></el-icon>
            完成编辑
        </button>
        </div>
      </div>
    </div>

    <!-- 第四层：设备列表和图片展示 -->
    <div class="content-container">
      <!-- 左侧：设备列表 -->
      <div class="device-list-panel">
        <div class="device-tree">
          <div 
            v-for="device in categoryDevices" 
            :key="device.id" 
            class="device-node"
          >
            <!-- 一级设备（分类） -->
            <div 
              v-if="device.isCategory" 
              class="category-node"
              :class="{ active: selectedDevice?.id === device.id }"
              @click="handleCategoryClick(device)"
            >
              <el-icon class="expand-icon" :class="{ expanded: expandedCategories.includes(device.id) }">
                <ArrowRight />
              </el-icon>
              <span class="node-text">{{ device.name }}</span>
            </div>
            
            <!-- 二级设备列表 -->
            <div 
              v-if="device.isCategory && expandedCategories.includes(device.id)" 
              class="subcategory-list"
            >
              <!-- 有子设备时显示子设备列表 -->
              <div 
                v-if="device.children && device.children.length > 0"
              >
                <div 
                  v-for="subDevice in device.children" 
                  :key="subDevice.id"
                  class="device-item"
                  :class="{ active: selectedDevice?.id === subDevice.id }"
                  @click="selectDevice(subDevice)"
                >
                  {{ subDevice.name }}
                </div>
              </div>
              
              <!-- 空分类提示 -->
              <div 
                v-else
                class="empty-category-hint"
              >
                <span class="hint-text">此分类暂无设备，可以添加新设备或删除此分类</span>
              </div>
            </div>

            <!-- 直接设备（非分类） -->
            <div 
              v-if="!device.isCategory" 
              class="device-item"
              :class="{ active: selectedDevice?.id === device.id }"
              @click="selectDevice(device)"
            >
              {{ device.name }}
            </div>
          </div>
          
          <div v-if="!categoryDevices.length" class="empty-list">
            请选择设备分类
          </div>
        </div>
      </div>

      <!-- 右侧：文件展示区域 -->
      <div class="file-display-panel">
        <div v-if="selectedDevice && !selectedDevice.isCategory && !isDeviceCategory(selectedDevice) && (selectedDevice.images?.length > 0 || selectedDevice.coordinateFiles?.length > 0 || selectedDevice.coordinateLog)" class="file-gallery">
          
          <!-- 分类文件夹展示 -->
          <div v-if="!isEditingImages && deviceImageFolders.length > 0">
            <!-- 文件夹卡片区域 -->
            <div class="folder-container">
              <div v-for="(folder, folderIndex) in deviceImageFolders" :key="`folder_${folderIndex}`" class="folder-section">
                <!-- 文件夹标题 -->
                <div class="folder-header" @click="toggleFolder(folderIndex)">
                  <el-icon class="folder-icon" :class="{ expanded: expandedFolders.includes(folderIndex) }">
                    <ArrowRight />
                  </el-icon>
                  <el-icon class="folder-type-icon">
                    <Folder />
                  </el-icon>
                  <span class="folder-name">{{ folder.name }}</span>
                  <span class="folder-count">({{ folder.images.length }} 张图片)</span>
                </div>
                
                <!-- 文件夹内容 -->
                <div v-if="expandedFolders.includes(folderIndex)" class="folder-content">
                  <div class="folder-images">
                    <div 
                      v-for="(image, imageIndex) in folder.images" 
                      :key="`folder_${folderIndex}_img_${image.id || imageIndex}`"
                      class="file-card image-card"
                      @click="handleFilePreview(image, 'image')"
                    >
                      <div class="file-container image-container">
                        <img :src="image.url || image.thumbnail" :alt="image.name" />
                        <div class="file-overlay">
                          <div class="file-type-badge image-badge">📷 图片</div>
                          <div class="file-action">点击放大</div>
                        </div>
                      </div>
                      <div class="file-caption">{{ image.name || `图片 ${imageIndex + 1}` }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 坐标文件单独显示 -->
            <div v-if="selectedDevice.coordinateLog" class="coordinate-file-section">
              <div 
            class="file-card coordinate-card"
                @click="handleFilePreview(selectedDevice.coordinateLog, 'coordinates')"
              >
                <!-- 下载按钮 -->
                <button 
                  class="download-coordinate-btn"
                  @click.stop="downloadCoordinateFile(selectedDevice.coordinateLog)"
                  title="下载坐标文件"
                >
                  <el-icon><Download /></el-icon>
                </button>
                
            <div class="file-container coordinate-container">
              <div class="coordinate-preview">
                <div class="coordinate-icon">📝</div>
                <div class="coordinate-info">
                  <div class="coordinate-title">坐标文件</div>
                      <div class="coordinate-desc">点击查看内容</div>
                </div>
              </div>
              <div class="file-overlay">
                    <div class="file-type-badge coordinate-badge">📝 TXT</div>
                    <div class="file-action">点击打开</div>
              </div>
            </div>
                <div class="file-caption">{{ selectedDevice.coordinateLog.name || '坐标文件' }}</div>
              </div>
            </div>
          </div>

          <!-- 编辑模式下的图片展示（保持原有逻辑） -->
          <div v-else-if="isEditingImages" class="edit-mode-gallery">
            <!-- 分类文件夹展示（编辑模式） -->
            <div v-if="deviceImageFolders.length > 0" class="folder-container">
              <div v-for="(folder, folderIndex) in deviceImageFolders" :key="`edit_folder_${folderIndex}`" class="folder-section">
                <!-- 文件夹标题 -->
                <div class="folder-header" @click="toggleFolder(folderIndex)">
                  <el-icon class="folder-icon" :class="{ expanded: expandedFolders.includes(folderIndex) }">
                    <ArrowRight />
                  </el-icon>
                  <el-icon class="folder-type-icon">
                    <Folder />
                  </el-icon>
                  <span class="folder-name">{{ folder.name }}</span>
                  <span class="folder-count">({{ folder.images.length }} 张图片)</span>
                </div>
                
                <!-- 文件夹内容（编辑模式） -->
                <div v-if="expandedFolders.includes(folderIndex)" class="folder-content">
                  <div class="folder-images">
                    <div 
                      v-for="(image, imageIndex) in folder.images" 
                      :key="`edit_folder_${folderIndex}_img_${image.id || imageIndex}`"
                      class="file-card image-card edit-mode"
                      :class="{ 'clickable': coordinatesImported }"
                      @click="handleImageClick(image, getGlobalImageIndex(folderIndex, imageIndex))"
                    >
                      <!-- 编辑模式下的删除按钮 -->
                      <button 
                        class="delete-image-btn"
                        @click.stop="deleteDeviceImage(imageIndex, folderIndex)"
                        title="删除图片"
                      >
                        <el-icon><Close /></el-icon>
                      </button>
                      
                      <div class="file-container image-container">
                        <img :src="image.url || image.thumbnail" :alt="image.name" />
                        <div v-if="!coordinatesImported" class="edit-overlay">
                          <div class="edit-info">编辑模式</div>
                </div>
                        <div v-else class="clickable-overlay">
                          <div class="clickable-info">点击编辑坐标</div>
              </div>
              </div>
                      <div class="file-caption">{{ image.name || `图片 ${imageIndex + 1}` }}</div>
            </div>
                  </div>
                </div>
              </div>
          </div>

            <!-- 如果没有分类文件夹，显示原有的图片列表 -->
            <div v-else>
              <div 
                v-for="(image, index) in selectedDevice.images || []" 
                :key="`img_${image.id || index}`"
                class="file-card image-card edit-mode"
                :class="{ 'clickable': coordinatesImported && isEditingImages }"
                @click="handleImageClick(image, index)"
              >
                <!-- 编辑模式下的删除按钮 -->
                <button 
                  class="delete-image-btn"
                  @click.stop="deleteDeviceImage(index)"
                  title="删除图片"
                >
                  <el-icon><Close /></el-icon>
                </button>
                
                <div class="file-container image-container">
                  <img :src="image.url || image.thumbnail" :alt="image.name" />
                  <div v-if="!coordinatesImported" class="edit-overlay">
                    <div class="edit-info">编辑模式</div>
                  </div>
                  <div v-else class="clickable-overlay">
                    <div class="clickable-info">点击编辑坐标</div>
                  </div>
                </div>
                <div class="file-caption">{{ image.name || `图片 ${index + 1}` }}</div>
              </div>
            </div>
            
            <!-- 编辑模式下的添加按钮 -->
            <div 
              class="file-card add-image-card"
              @click="addDeviceImage"
            >
              <div class="file-container add-container">
                <div class="add-icon">
                  <el-icon size="48"><Plus /></el-icon>
                </div>
                <div class="add-text">添加图片</div>
              </div>
              <div class="file-caption">点击添加新图片</div>
            </div>
          </div>
          
          <!-- 非编辑模式下的原有图片展示 -->
          <div v-else>
            <div 
              v-for="(image, index) in selectedDevice.images || []" 
              :key="`normal_img_${image.id || index}`"
              class="file-card image-card"
                @click="handleFilePreview(image, 'image')"
              >
                <div class="file-container image-container">
                  <img :src="image.url || image.thumbnail" :alt="image.name" />
                  <div class="file-overlay">
                    <div class="file-type-badge image-badge">📷 图片</div>
                    <div class="file-action">点击放大</div>
                  </div>
                </div>
                <div class="file-caption">{{ image.name || `图片 ${index + 1}` }}</div>
            </div>
          </div>
          
          <!-- 其他坐标文件 -->
          <div 
            v-for="(coordFile, index) in selectedDevice.coordinateFiles || []" 
            :key="`coord_${index}`"
            class="file-card coordinate-card"
            @click="handleFilePreview(coordFile, 'coordinates')"
          >
            <div class="file-container coordinate-container">
              <div class="coordinate-preview">
                <div class="coordinate-icon">📝</div>
                <div class="coordinate-info">
                  <div class="coordinate-title">坐标文件</div>
                  <div class="coordinate-desc">点击查看内容</div>
                </div>
              </div>
              <div class="file-overlay">
                <div class="file-type-badge coordinate-badge">📝 TXT</div>
                <div class="file-action">点击打开</div>
              </div>
            </div>
            <div class="file-caption">{{ coordFile.name || `坐标文件 ${index + 1}` }}</div>
          </div>
        </div>
        <div v-else class="empty-display">
          <div class="empty-content">
            <el-icon size="64" class="empty-icon"><Document /></el-icon>
            <p v-if="!selectedDevice" class="empty-text">请选择设备查看文件</p>
            <p v-else-if="isDeviceCategory(selectedDevice)" class="empty-text">请选择具体设备查看图片文件</p>
            <p v-else class="empty-text">该设备暂无文件</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑设备对话框 -->
    <DeviceDialog
      v-model="showDeviceDialog"
      :device="editingDevice"
      @success="handleDeviceSuccess"
    />

    <!-- 编辑设备信息对话框 -->
    <DeviceInfoDialog
      v-model="showDeviceInfoDialog"
      :device="selectedDevice"
      @success="handleDeviceInfoSuccess"
    />

    <!-- 登录对话框 -->
    <LoginDialog
      v-model="showLoginDialogVisible"
      @login-success="handleLoginSuccess"
    />

    <!-- 注册对话框 -->
    <RegisterDialog
      v-model="showRegisterDialogVisible"
      @register-success="handleRegisterSuccess"
    />
    
    <!-- Footer 页脚 -->
    <Footer />
  </div>
</template>

<script setup>
/**
 * 主页面组件
 * 
 * 核心功能：
 * - 设备列表展示
 * - 设备管理操作
 * - 导航到模拟界面
 */

import { ref, computed, onMounted, onUnmounted, nextTick, h } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDeviceStore } from '@/stores/device'
import { DEVICE_CATEGORIES } from '@/utils/constants'
import * as authApi from '@/api/auth'
import DeviceDialog from '@/components/DeviceDialog.vue'
import DeviceInfoDialog from '@/components/DeviceInfoDialog.vue'
import LoginDialog from '@/components/LoginDialog.vue'
import RegisterDialog from '@/components/RegisterDialog.vue'
import Footer from '@/components/Footer.vue'

console.log('Home页面组件加载')

const router = useRouter()
const deviceStore = useDeviceStore()

// 响应式数据
const searchKeyword = ref('')
const selectedCategory = ref('emergency_life_support') // 默认选择急救与生命支持
const selectedDevice = ref(null)
const displayImage = ref('')
const showDeviceDialog = ref(false)
const showDeviceInfoDialog = ref(false) // 设备信息编辑对话框
const editingDevice = ref(null)
const expandedCategories = ref([]) // 展开的分类
const isEditingImages = ref(false) // 图片编辑模式
const coordinatesImported = ref(false) // 坐标是否已导入
const imageCoordinates = ref({}) // 存储每张图片的坐标信息
const isScrolled = ref(false) // 导航栏滚动状态
const deviceImageFolders = ref([]) // 设备图片分类文件夹
const expandedFolders = ref([]) // 展开的文件夹索引

// 认证相关数据
const isLoggedIn = ref(false)
const currentUser = ref(null)
const showLoginDialogVisible = ref(false)
const showRegisterDialogVisible = ref(false)

// 设备分类数据（添加图标路径）
const deviceCategories = computed(() => [
  {
    id: 'emergency_life_support',
    name: '急救与生命支持',
    iconPath: '/icons/jijiu.png'
  },
  {
    id: 'in_vitro_diagnostics',
    name: '体外诊断',
    iconPath: '/icons/tiwai.png'
  },
  {
    id: 'infusion_pump',
    name: '输注泵',
    iconPath: '/icons/shuzhu.png'
  },
  {
    id: 'medical_imaging',
    name: '医学影像',
    iconPath: '/icons/yixue.png'
  },
  {
    id: 'surgical_equipment',
    name: '外科设备',
    iconPath: '/icons/waike.png'
  }
])

// 计算属性
const selectedCategoryName = computed(() => {
  const category = deviceCategories.value.find(cat => cat.id === selectedCategory.value)
  return category ? category.name : ''
})

// 判断删除按钮是否应该禁用
const isDeleteDisabled = computed(() => {
  if (!selectedDevice.value) return true
  
  // 如果是有子设备的分类，禁用删除按钮
  const isCategory = selectedDevice.value.isCategory || selectedDevice.value.type === 'category'
  const hasChildren = selectedDevice.value.children && selectedDevice.value.children.length > 0
  
  return isCategory && hasChildren
})

// 判断是否可以编辑设备信息
const canEditDeviceInfo = computed(() => {
  if (!selectedDevice.value) return false
  
  // 只有具体设备（二级设备）才能编辑信息
  const isCategory = selectedDevice.value.isCategory || selectedDevice.value.type === 'category'
  return !isCategory
})

// 判断是否可以编辑设备图片
const canEditDeviceImages = computed(() => {
  if (!selectedDevice.value) return false
  
  // 检查是否为分类设备
  const isCategory = selectedDevice.value.isCategory || selectedDevice.value.type === 'category'
  if (isCategory) return false
  
  // 检查是否有图片
  return selectedDevice.value.images && selectedDevice.value.images.length > 0
})

const categoryDevices = computed(() => {
  if (!selectedCategory.value) return []
  return deviceStore.devices.filter(device => device.category === selectedCategory.value)
})

const searchResults = computed(() => {
  if (!searchKeyword.value.trim()) return []
  const keyword = searchKeyword.value.toLowerCase()
  const results = []
  
  deviceStore.devices.forEach(device => {
    // 搜索一级设备
    if (device.name.toLowerCase().includes(keyword)) {
      results.push(device)
    }
    // 搜索二级设备
    if (device.children) {
      device.children.forEach(child => {
        if (child.name.toLowerCase().includes(keyword)) {
          results.push(child)
        }
      })
    }
  })
  
  return results
})

// 方法定义
// 判断设备是否为分类
const isDeviceCategory = (device) => {
  if (!device) return false
  
  // 检查是否有isCategory标记
  if (device.isCategory === true) return true
  
  // 检查是否有type为category
  if (device.type === 'category') return true
  
  // 检查是否有children属性（通常分类设备会有子设备）
  if (device.children && Array.isArray(device.children)) return true
  
  return false
}

const handleSearch = () => {
  console.log('搜索设备:', searchKeyword.value)
  if (searchKeyword.value.trim()) {
    const results = searchResults.value
    if (results.length > 0) {
      // 显示第一个搜索结果
      const firstResult = results[0]
      selectedDevice.value = firstResult
      // 如果是子设备，自动展开父分类
      if (firstResult.parentId && !expandedCategories.value.includes(firstResult.parentId)) {
        expandedCategories.value.push(firstResult.parentId)
      }
      ElMessage.success(`找到 ${results.length} 个相关设备`)
    } else {
      selectedDevice.value = null
      ElMessage.info('未找到相关设备')
    }
  } else {
    selectedDevice.value = null
  }
}

const selectCategory = (categoryId) => {
  console.log('选择设备分类:', categoryId)
  selectedCategory.value = categoryId
  selectedDevice.value = null
  displayImage.value = ''
  expandedCategories.value = [] // 清空展开状态
}

const toggleCategory = (categoryId) => {
  console.log('切换分类展开:', categoryId)
  const index = expandedCategories.value.indexOf(categoryId)
  if (index > -1) {
    expandedCategories.value.splice(index, 1)
  } else {
    expandedCategories.value.push(categoryId)
  }
}

const handleCategoryClick = (device) => {
  console.log('点击一级列表:', device.name)
  
  // 1. 选中该设备（使删除和编辑按钮可用）
  selectDevice(device)
  
  // 2. 切换展开/收起状态
  toggleCategory(device.id)
}

const selectDevice = (device) => {
  console.log('选择设备:', device.name)
  selectedDevice.value = device
  
  // 对设备图片进行分类
  if (device && !device.isCategory && !isDeviceCategory(device)) {
    classifyDeviceImages(device)
  } else {
    deviceImageFolders.value = []
  expandedFolders.value = []
  }
}

// 设备图片分类函数
const classifyDeviceImages = (device) => {
  console.log('开始对设备图片进行分类:', device.name)
  
  try {
    const classificationResult = deviceStore.classifyDeviceImages(device)
    deviceImageFolders.value = classificationResult.folders
    
    // 默认不展开文件夹
    expandedFolders.value = []
    
    console.log('图片分类完成，文件夹数量:', classificationResult.folders.length)
  } catch (error) {
    console.error('图片分类失败:', error)
    deviceImageFolders.value = []
    expandedFolders.value = []
  }
}

const showAddDeviceDialog = () => {
  console.log('显示添加设备对话框，当前分类:', selectedCategory.value)
  // 确保清空编辑设备，并设置默认分类
  editingDevice.value = selectedCategory.value ? { category: selectedCategory.value } : null
  showDeviceDialog.value = true
}

// 编辑设备信息（名称和类型）
const editDeviceInfo = () => {
  if (!selectedDevice.value) {
    ElMessage.warning('请先选择要编辑的设备')
    return
  }
  
  // 检查是否为分类设备
  if (isDeviceCategory(selectedDevice.value)) {
    ElMessage.warning('无法编辑分类设备，请选择具体的设备进行编辑')
    return
  }
  
  console.log('编辑设备信息:', selectedDevice.value.name)
  
  // 打开设备信息编辑对话框
  showDeviceInfoDialog.value = true
}

// 编辑设备图片
const editSelectedDevice = () => {
  if (!selectedDevice.value) {
    ElMessage.warning('请先选择要编辑的设备')
    return
  }
  
  // 检查是否为分类设备
  if (isDeviceCategory(selectedDevice.value)) {
    ElMessage.warning('无法编辑分类设备的图片，请选择具体的设备进行编辑')
    return
  }
  
  console.log('编辑设备图片:', selectedDevice.value.name)
  
  // 检查是否有图片可编辑
  if (!selectedDevice.value.images || selectedDevice.value.images.length === 0) {
    ElMessage.warning('该设备暂无图片，请先添加图片')
    return
  }
  
  // 切换到图片编辑模式
  isEditingImages.value = true
  ElMessage.info('已进入图片编辑模式，可以删除或添加设备图片')
}

// 退出图片编辑模式
const exitImageEditMode = () => {
  isEditingImages.value = false
  coordinatesImported.value = false
  imageCoordinates.value = {}
  
  // 重新分类设备图片
  if (selectedDevice.value && !selectedDevice.value.isCategory && !isDeviceCategory(selectedDevice.value)) {
    classifyDeviceImages(selectedDevice.value)
  }
  
  ElMessage.success('已退出图片编辑模式')
}

// 切换文件夹展开/收起状态
const toggleFolder = (folderIndex) => {
  const index = expandedFolders.value.indexOf(folderIndex)
  if (index > -1) {
    expandedFolders.value.splice(index, 1)
  } else {
    expandedFolders.value.push(folderIndex)
  }
}

// 导入坐标信息
const importCoordinates = async () => {
  if (!selectedDevice.value || !selectedDevice.value.coordinateLog) {
    ElMessage.warning('该设备没有坐标文件，请先上传log.txt文件')
    return
  }
  
  try {
    console.log('开始导入坐标信息')
    
    // 解析log.txt内容
    const logContent = selectedDevice.value.coordinateLog.content
    if (!logContent) {
      ElMessage.error('坐标文件内容为空')
      return
    }
    
    // 使用Store中的parseLogContent函数解析
    const coordinateData = deviceStore.parseLogContent(logContent)
    
    if (!coordinateData || Object.keys(coordinateData).length === 0) {
      ElMessage.error('坐标文件解析失败或内容为空')
      return
    }
    
    console.log('解析到的坐标数据:', coordinateData)
    
    // 处理坐标数据，提取每个页面的信息
    const processedCoordinates = {}
    
    for (const [pageKey, pageData] of Object.entries(coordinateData)) {
      if (Array.isArray(pageData) && pageData.length > 0) {
        // 第一个元素包含页面信息（orgin_name）
        const pageInfo = pageData[0]
        // 其余元素是按钮信息，需要过滤掉只有orgin_name的元素
        const buttons = pageData.slice(1).filter(btn => 
          btn && 
          typeof btn === 'object' && 
          btn.x !== undefined && 
          btn.y !== undefined &&
          btn.width !== undefined &&
          btn.height !== undefined
        )
        
        processedCoordinates[pageKey] = {
          orgin_name: pageInfo.orgin_name || pageKey,
          buttons: buttons
        }
        
        console.log(`页面 ${pageKey}:`, {
          orgin_name: pageInfo.orgin_name,
          buttonCount: buttons.length,
          buttons: buttons
        })
      }
    }
    
    imageCoordinates.value = processedCoordinates
    coordinatesImported.value = true
    
    console.log('处理后的坐标信息:', processedCoordinates)
    
    // 构建控件库
    console.log('开始构建控件库...')
    const widgets = deviceStore.buildWidgetLibrary(selectedDevice.value)
    console.log('控件库构建完成，控件数量:', widgets.length)
    
    ElMessage.success(`成功导入 ${Object.keys(processedCoordinates).length} 个页面的坐标信息`)
    
  } catch (error) {
    console.error('导入坐标信息失败:', error)
    ElMessage.error('导入坐标信息失败：' + error.message)
  }
}

// 计算图片的全局索引（用于删除操作）
const getGlobalImageIndex = (folderIndex, imageIndex) => {
  let globalIndex = 0
  
  // 计算前面文件夹的图片总数
  for (let i = 0; i < folderIndex; i++) {
    globalIndex += deviceImageFolders.value[i].images.length
  }
  
  // 加上当前文件夹内的索引
  globalIndex += imageIndex
  
  return globalIndex
}

// 删除单张图片
const deleteDeviceImage = async (imageIndex, folderIndex = null) => {
  if (!selectedDevice.value || !selectedDevice.value.images) {
    return
  }
  
  // 如果提供了文件夹索引，计算全局索引
  const actualIndex = folderIndex !== null ? getGlobalImageIndex(folderIndex, imageIndex) : imageIndex
  const image = selectedDevice.value.images[actualIndex]
  
  if (!image) {
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除图片"${image.name}"吗？此操作不可恢复。`,
      '确认删除图片',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    console.log('删除设备图片:', image.name)
    
    // 调用Store方法删除图片
    await deviceStore.deleteDeviceImage(selectedDevice.value.id, actualIndex)
    
    ElMessage.success(`图片"${image.name}"删除成功`)
    
    // 重新分类剩余图片
    if (selectedDevice.value.images && selectedDevice.value.images.length > 0) {
      classifyDeviceImages(selectedDevice.value)
  } else {
      // 如果删除后没有图片了，清空分类并退出编辑模式
      deviceImageFolders.value = []
      expandedFolders.value = []
      isEditingImages.value = false
      ElMessage.info('所有图片已删除，已退出编辑模式')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除图片失败:', error)
      ElMessage.error('删除图片失败')
    }
  }
}

// 添加新图片
const addDeviceImage = () => {
  if (!selectedDevice.value) {
    return
  }
  
  // 创建文件输入元素
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/jpeg,image/jpg,image/png'
  input.multiple = false
  
  input.onchange = async (event) => {
    const file = event.target.files[0]
    if (!file) {
      return
    }
    
    // 验证文件大小和类型
    if (file.size > 5 * 1024 * 1024) {
      ElMessage.error('图片文件大小不能超过5MB')
      return
    }
    
    if (!['image/jpeg', 'image/jpg', 'image/png'].includes(file.type)) {
      ElMessage.error('只支持JPG、JPEG、PNG格式的图片')
      return
    }
    
    try {
      console.log('添加设备图片:', file.name)
      
      // 调用Store方法添加图片
      await deviceStore.addDeviceImage(selectedDevice.value.id, file)
      
      ElMessage.success(`图片"${file.name}"添加成功`)
      
      // 重新分类图片
      classifyDeviceImages(selectedDevice.value)
      
    } catch (error) {
      console.error('添加图片失败:', error)
      ElMessage.error('添加图片失败')
    }
  }
  
  input.click()
}

// 下载坐标文件
const downloadCoordinateFile = (coordinateFile) => {
  if (!coordinateFile) {
    ElMessage.warning('坐标文件不存在')
    return
  }
  
  try {
    console.log('下载坐标文件:', coordinateFile.name)
    
    // 获取文件内容
    const content = coordinateFile.content || '{}'
    const fileName = coordinateFile.name || 'coordinates.txt'
    
    // 创建Blob对象
    const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
    
    // 创建下载链接
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    // 清理URL对象
    URL.revokeObjectURL(url)
    
    ElMessage.success(`坐标文件"${fileName}"下载成功`)
    
  } catch (error) {
    console.error('下载坐标文件失败:', error)
    ElMessage.error('下载坐标文件失败')
  }
}

const deleteSelectedDevice = async () => {
  if (!selectedDevice.value) {
    ElMessage.warning('请先选择要删除的设备')
    return
  }
  
  try {
    // 判断是删除一级列表还是二级记录
    const isCategory = selectedDevice.value.isCategory || selectedDevice.value.type === 'category'
    const childrenCount = selectedDevice.value.children?.length || 0
    
    // 如果是有子设备的分类，禁止删除
    if (isCategory && childrenCount > 0) {
      ElMessage.warning(`无法删除分类"${selectedDevice.value.name}"，请先删除该分类下的所有设备`)
      return
    }
    
    let confirmMessage = ''
    if (isCategory) {
      confirmMessage = `确定要删除空分类"${selectedDevice.value.name}"吗？此操作不可恢复。`
    } else {
      confirmMessage = `确定要删除设备"${selectedDevice.value.name}"吗？此操作不可恢复。`
    }
    
    await ElMessageBox.confirm(
      confirmMessage,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const deleteResult = await deviceStore.deleteDevice(selectedDevice.value.id)
    
    // 根据删除类型显示不同的成功消息
    if (isCategory) {
      ElMessage.success(`空分类"${selectedDevice.value.name}"删除成功`)
    } else if (deleteResult?.categoryBecameEmpty) {
      ElMessage.success(`设备"${selectedDevice.value.name}"删除成功，分类已变为空分类`)
    } else {
      ElMessage.success('设备删除成功')
    }
    
    // 清除选中状态
    selectedDevice.value = null
    displayImage.value = ''
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除设备失败:', error)
      ElMessage.error('删除设备失败')
    }
  }
}

const handleDeviceSuccess = () => {
  console.log('设备操作成功')
  // 对话框关闭由DeviceDialog内部处理，避免重复操作
  // 刷新设备列表显示
  nextTick(() => {
    console.log('刷新设备列表显示')
    // 强制触发响应式更新
    if (selectedCategory.value) {
      const currentCategory = selectedCategory.value
      selectedCategory.value = ''
      nextTick(() => {
        selectedCategory.value = currentCategory
      })
    }
  })
}

// 处理设备信息编辑成功
const handleDeviceInfoSuccess = () => {
  console.log('设备信息更新成功')
  
  // 重新加载设备数据，更新视图
  nextTick(() => {
    console.log('刷新设备列表显示')
    
    // 清空选中的设备，因为设备可能已经迁移到其他类型下
    const updatedDeviceId = selectedDevice.value?.id
    selectedDevice.value = null
    
    // 强制触发响应式更新
    if (selectedCategory.value) {
      const currentCategory = selectedCategory.value
      selectedCategory.value = ''
      nextTick(() => {
        selectedCategory.value = currentCategory
        
        // 尝试重新选中更新后的设备
        if (updatedDeviceId) {
          // 在当前分类下查找设备
          const devices = deviceStore.devices.filter(d => d.category === currentCategory)
          for (const device of devices) {
            if (device.children && Array.isArray(device.children)) {
              const foundDevice = device.children.find(child => child.id === updatedDeviceId)
              if (foundDevice) {
                selectedDevice.value = foundDevice
                console.log('重新选中设备:', foundDevice.name)
                break
              }
            }
          }
        }
      })
    }
  })
}

// 处理文件预览（图片放大、TXT文件查看）
const handleFilePreview = (file, fileType) => {
  console.log('预览文件:', file.name, '类型:', fileType)
  
  if (fileType === 'image') {
    // 显示图片放大对话框
    showImagePreview(file)
  } else if (fileType === 'coordinates') {
    // 显示坐标文件内容
    showCoordinateFileContent(file)
  }
}

// 显示图片放大
const showImagePreview = (file) => {
  ElMessageBox({
    title: file.name || '图片预览',
    message: h('div', {
      style: 'text-align: center; padding: 20px;'
    }, [
      h('img', {
        src: file.url || file.thumbnail,
        style: 'max-width: 100%; max-height: 70vh; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); cursor: zoom-in;',
        onClick: () => {
          // 可以在这里添加更大的放大功能
          window.open(file.url || file.thumbnail, '_blank')
        }
      })
    ]),
    showCancelButton: false,
    confirmButtonText: '关闭',
    customClass: 'image-preview-dialog'
  })
}

// 处理图片点击
const handleImageClick = (image, index) => {
  // 如果不在编辑模式或未导入坐标，使用原来的预览功能
  if (!isEditingImages.value || !coordinatesImported.value) {
    if (!isEditingImages.value) {
      handleFilePreview(image, 'image')
    }
    return
  }
  
  // 在编辑模式且已导入坐标时，跳转到坐标编辑器
  console.log('点击图片进入坐标编辑器:', image.name)
  
  // 查找对应的坐标信息
  const imageNameWithoutExt = image.name.replace(/\.[^/.]+$/, "")
  let coordinateInfo = null
  
  // 尝试多种匹配方式查找坐标信息
  const possibleKeys = [image.name, imageNameWithoutExt, image.name.toLowerCase(), imageNameWithoutExt.toLowerCase()]
  
  for (const key of possibleKeys) {
    if (imageCoordinates.value[key]) {
      coordinateInfo = imageCoordinates.value[key]
      break
    }
  }
  
  if (!coordinateInfo) {
    ElMessage.warning(`未找到图片"${image.name}"对应的坐标信息`)
    return
  }
  
  // 跳转到坐标编辑器页面
  router.push({
    name: 'CoordinateEditor',
    params: {
      deviceId: selectedDevice.value.id,
      imageId: image.id || index
    },
    query: {
      imageName: image.name,
      imageUrl: image.url || image.thumbnail,
      orginName: coordinateInfo.orgin_name,
      coordinateData: JSON.stringify(coordinateInfo),
      deviceData: JSON.stringify({
        id: selectedDevice.value.id,
        name: selectedDevice.value.name,
        images: selectedDevice.value.images || [],
        coordinateLog: selectedDevice.value.coordinateLog
      })
    }
  })
}

// 显示坐标文件内容
const showCoordinateFileContent = (file) => {
  const content = file.content || file.url || '文件内容为空'
  ElMessageBox({
    title: `坐标文件: ${file.name || '未命名'}`,
    message: h('div', {
      style: 'max-height: 400px; overflow-y: auto;'
    }, [
      h('pre', {
        style: 'background: #f8f9fa; padding: 15px; border-radius: 6px; font-family: "Courier New", monospace; font-size: 12px; line-height: 1.6; white-space: pre-wrap; word-wrap: break-word; border: 1px solid #e9ecef; margin: 0;'
      }, content)
    ]),
    showCancelButton: false,
    confirmButtonText: '关闭',
    customClass: 'coordinate-file-dialog'
  })
}

// 认证相关方法
const checkLoginStatus = () => {
  console.log('检查登录状态')
  
  // 检查token是否存在
  const token = localStorage.getItem('token')
  if (token) {
    isLoggedIn.value = true
    
    // 获取用户信息
    const userInfo = localStorage.getItem('userInfo')
    if (userInfo) {
      try {
        currentUser.value = JSON.parse(userInfo)
        console.log('已登录用户:', currentUser.value)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        // 清除无效数据
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        isLoggedIn.value = false
      }
    }
  } else {
    isLoggedIn.value = false
    currentUser.value = null
  }
}

const showLoginDialog = () => {
  console.log('显示登录对话框')
  showLoginDialogVisible.value = true
}

const showRegisterDialog = () => {
  console.log('显示注册对话框')
  showRegisterDialogVisible.value = true
}

const handleLoginSuccess = (user) => {
  console.log('登录成功:', user.username)
  
  // 设置登录状态
  isLoggedIn.value = true
  currentUser.value = user
  
  // 保存到localStorage（路由守卫需要检查）
  localStorage.setItem('token', 'mock-token-' + Date.now())
  localStorage.setItem('userInfo', JSON.stringify(user))
  
  ElMessage.success(`欢迎回来，${user.realName || user.username}！`)
}

const handleRegisterSuccess = (user) => {
  console.log('注册成功:', user.username)
  ElMessage.success('注册成功，请登录')
  // 注册成功后可以自动显示登录对话框
  setTimeout(() => {
    showLoginDialog()
  }, 1000)
}

// 跳转到控制台页面
const goToConsole = () => {
  console.log('跳转到控制台页面')
  router.push('/console')
}

const handleUserCommand = async (command) => {
  console.log('用户菜单命令:', command)
  
  switch (command) {
    case 'profile':
      ElMessage.info('个人资料功能开发中')
      break
    case 'settings':
      ElMessage.info('设置功能开发中')
      break
    case 'logout':
      try {
        // 清除localStorage中的认证信息
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        
        // 清除组件状态
        isLoggedIn.value = false
        currentUser.value = null
        
        ElMessage.success('已退出登录')
      } catch (error) {
        console.error('退出登录失败:', error)
        ElMessage.error('退出登录失败')
      }
      break
  }
}

// 处理滚动事件
const handleScroll = () => {
  isScrolled.value = window.scrollY > 50
}

// 处理从坐标编辑器返回的状态恢复
const handleReturnFromEditor = () => {
  const query = router.currentRoute.value.query
  
  if (query.editMode === 'true' && query.deviceId) {
    console.log('从坐标编辑器返回，恢复编辑状态')
    
    // 查找并选择对应的设备
    const targetDeviceId = query.deviceId
    let targetDevice = null
    
    for (const device of deviceStore.devices) {
      if (device.id === targetDeviceId) {
        targetDevice = device
        break
      }
      if (device.children) {
        for (const child of device.children) {
          if (child.id === targetDeviceId) {
            targetDevice = child
            break
          }
        }
        if (targetDevice) break
      }
    }
    
    if (targetDevice) {
      console.log('找到目标设备:', targetDevice.name)
      selectedDevice.value = targetDevice
      selectedCategory.value = targetDevice.category
      isEditingImages.value = true
      
      // 重新分类设备图片，恢复文件夹结构
      if (targetDevice && !targetDevice.isCategory && targetDevice.images && targetDevice.images.length > 0) {
        console.log('恢复设备图片分类...')
        classifyDeviceImages(targetDevice)
      }
      
      if (query.coordinatesImported === 'true') {
        // 重新导入坐标信息
        console.log('重新导入坐标信息...')
        importCoordinates()
      }
      
      // 清除URL参数
      router.replace({ name: 'Home' })
    } else {
      console.warn('未找到目标设备:', targetDeviceId)
    }
  }
}

// 生命周期
onMounted(async () => {
  console.log('Home页面挂载，开始加载设备列表')
  checkLoginStatus()
  
  // 添加滚动事件监听
  window.addEventListener('scroll', handleScroll)
  
  try {
    await deviceStore.fetchDevices()
    // 处理从坐标编辑器返回的状态
    handleReturnFromEditor()
  } catch (error) {
    console.error('加载设备列表失败:', error)
    ElMessage.error('加载设备列表失败')
  }
})

// 清理事件监听
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped>
/* 整体容器 */
.mindray-system {
  width: 100vw;
  min-height: 100vh;
  background: #ffffff;
  display: flex;
  flex-direction: column;
  position: relative;
}

/* 第一层：顶部导航栏 */
.top-navigation {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  padding: 0 40px;
  height: 80px;
  background: #ffffff;
  border-bottom: 1px solid #e5e7eb;
  z-index: 100;
  transition: all 0.3s ease;
}

.top-navigation.scrolled {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
}

.logo-container {
  flex-shrink: 0;
  margin-right: 60px;
}

.mindray-logo {
  height: 70px;
  width: auto;
}

.nav-menu {
  display: flex;
  align-items: center;
  gap: 40px;
  flex: 1;
}

.nav-item {
  color: #333333;
  text-decoration: none;
  font-size: clamp(14px, 1.2vw, 18px);
  font-weight: 400;
  padding: 8px 0;
  transition: color 0.2s ease;
  cursor: pointer;
  white-space: nowrap;
}

.nav-item:hover {
  color: #d32f2f;
}

.auth-container {
  flex-shrink: 0;
}

.auth-buttons {
  display: flex;
  gap: 15px;
}

.auth-btn {
  padding: 8px 20px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: transparent;
  color: #333333;
}

.auth-btn:hover {
  background: #f5f5f5;
}

.logged-in-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.console-btn {
  padding: 8px 20px;
  border: 1px solid #3498db;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: #3498db;
  color: white;
  font-weight: 500;
}

.console-btn:hover {
  background: #2980b9;
  border-color: #2980b9;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(52, 152, 219, 0.3);
}

.user-dropdown .user-name {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: transparent;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  cursor: pointer;
  color: #333333;
  font-size: 14px;
  transition: all 0.2s ease;
}

.user-dropdown .user-name:hover {
  background: #f5f5f5;
}

/* 展示图片区域 */
.hero-banner {
  position: relative;
  width: 100%;
  height: 500px;
  margin-top: 80px; /* 为固定导航栏留出空间 */
  overflow: hidden;
}

.hero-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.hero-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(0, 0, 0, 0.4) 0%, rgba(0, 0, 0, 0.2) 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  text-align: center;
}

.hero-title {
  font-size: clamp(28px, 4vw, 46px);
  font-weight: 700;
  margin: 0 0 16px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.hero-subtitle {
  font-size: clamp(16px, 2vw, 24px);
  font-weight: 400;
  margin: 0;
  opacity: 0.9;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

/* 第二层：搜索栏和设备分类 */
.search-categories-container {
  display: flex;
  align-items: center;
  padding: 20px 40px;
  background: #ffffff;
  border-bottom: 1px solid #e5e7eb;
  gap: 40px;
}

.search-container {
  flex-shrink: 0;
}

.search-wrapper {
  display: flex;
  align-items: center;
  width: 300px;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.search-input {
  flex: 1;
  padding: 10px 15px;
  border: none;
  outline: none;
  font-size: 14px;
  background: #ffffff;
}

.search-input::placeholder {
  color: #999999;
}

.search-button {
  padding: 10px 15px;
  border: none;
  background: #d32f2f;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.2s ease;
}

.search-button:hover {
  background: #b71c1c;
}

.device-categories {
  display: flex;
  align-items: center;
  gap: 30px;
  flex: 1;
  justify-content: center;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px 20px;
  cursor: pointer;
  transition: all 0.2s ease;
  border-radius: 8px;
  min-width: 120px;
}

.category-item:hover .category-icon img,
.category-item.active .category-icon img {
  filter: brightness(0) saturate(100%) invert(18%) sepia(95%) saturate(7495%) hue-rotate(355deg) brightness(91%) contrast(91%);
}

.category-item:hover .category-name,
.category-item.active .category-name {
  color: #d32f2f;
}

.category-item:hover {
  background: transparent;
}

.category-item.active {
  background: transparent;
}

.category-icon {
  margin-bottom: 8px;
}

.category-icon img {
  width: 48px;
  height: 48px;
  object-fit: contain;
}

.category-name {
  font-size: clamp(12px, 1vw, 16px);
  font-weight: 500;
  text-align: center;
  line-height: 1.2;
  transition: color 0.2s ease;
}

/* 第三层：设备管理按钮 */
.management-container {
  padding: 20px 40px;
  background: #ffffff;
  border-bottom: 1px solid #e5e7eb;
}

.management-buttons {
  display: flex;
  gap: 15px;
}

.mgmt-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: clamp(8px, 1vw, 12px) clamp(16px, 2vw, 24px);
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #ffffff;
  color: #333333;
  font-size: clamp(12px, 1vw, 16px);
  cursor: pointer;
  transition: all 0.2s ease;
}

.mgmt-btn:hover:not(:disabled) {
  background: #f5f5f5;
  border-color: #ccc;
}

.mgmt-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.add-btn:hover:not(:disabled) {
  background: #e8f5e8;
  border-color: #4caf50;
  color: #4caf50;
}

.delete-btn:hover:not(:disabled) {
  background: #ffebee;
  border-color: #f44336;
  color: #f44336;
}

.edit-btn:hover:not(:disabled) {
  background: #e3f2fd;
  border-color: #2196f3;
  color: #2196f3;
}

.edit-info-btn:hover:not(:disabled) {
  background: #fff3e0;
  border-color: #ff9800;
  color: #ff9800;
}

/* 第四层：内容区域 */
.content-container {
  display: flex;
  flex: 1;
  min-height: 0;
}

/* 左侧设备列表 */
.device-list-panel {
  width: 400px;
  background: #ffffff;
  border-right: 1px solid #e5e7eb;
  overflow-y: auto;
}

.device-tree {
  padding: 20px;
}

.device-node {
  margin-bottom: 5px;
}

.category-node {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  border-radius: 4px;
  transition: background 0.2s ease;
  font-weight: 500;
  color: #333333;
}

.category-node:hover {
  background: #f5f5f5;
}

.expand-icon {
  margin-right: 8px;
  transition: transform 0.2s ease;
  color: #666666;
}

.expand-icon.expanded {
  transform: rotate(90deg);
}

.node-text {
  font-size: clamp(12px, 1vw, 16px);
}

.subcategory-list {
  margin-left: 24px;
  border-left: 2px solid #f0f0f0;
  padding-left: 16px;
}

.device-item {
  padding: clamp(8px, 1vw, 12px) 16px;
  margin: 2px 0;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s ease;
  font-size: clamp(12px, 1vw, 16px);
  color: #666666;
}

.device-item:hover {
  background: #f5f5f5;
  color: #333333;
}

.device-item.active {
  background: #e3f2fd;
  color: #1976d2;
  font-weight: 500;
}

.empty-list {
  padding: 40px 20px;
  text-align: center;
  color: #999999;
  font-size: 14px;
}

/* 空分类提示样式 */
.empty-category-hint {
  padding: 12px 16px;
  margin: 4px 0;
  background: #f8f9fa;
  border: 1px dashed #d1d5db;
  border-radius: 4px;
  text-align: center;
}

.hint-text {
  font-size: 12px;
  color: #6b7280;
  font-style: italic;
  line-height: 1.4;
}

/* 右侧图片展示区域 */
.image-display-panel {
  flex: 1;
  background: #ffffff;
  overflow-y: auto;
  padding: 20px;
}

.image-gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.image-card {
  background: #ffffff;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.image-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.image-container {
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  overflow: hidden;
}

.image-container img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.image-caption {
  padding: 15px;
  font-size: clamp(12px, 1vw, 16px);
  font-weight: 500;
  color: #333333;
  text-align: center;
  background: #ffffff;
}

.empty-display {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 400px;
}

.empty-content {
  text-align: center;
  color: #999999;
}

.empty-icon {
  margin-bottom: 16px;
  color: #cccccc;
}

.empty-text {
  font-size: clamp(14px, 1.2vw, 18px);
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-categories-container {
    padding: 15px 30px;
    gap: 30px;
  }
  
  .device-categories {
    gap: 20px;
  }
  
  .category-item {
    min-width: 100px;
    padding: 12px 15px;
  }
  
  .category-icon img {
    width: 40px;
    height: 40px;
  }
}

@media (max-width: 768px) {
  .top-navigation {
    flex-direction: column;
    height: auto;
    padding: 15px 20px;
    gap: 15px;
  }
  
  .nav-menu {
    gap: 20px;
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .search-categories-container {
    flex-direction: column;
    padding: 15px 20px;
    gap: 20px;
  }
  
  .device-categories {
    flex-wrap: wrap;
    gap: 15px;
  }
  
  .category-item {
    min-width: 80px;
  }
  
  .category-icon img {
    width: 32px;
    height: 32px;
  }
  
  .category-name {
    font-size: 12px;
  }
  
  .management-container {
    padding: 15px 20px;
  }
  
  .content-container {
    flex-direction: column;
  }
  
  .device-list-panel {
    width: 100%;
    max-height: 300px;
    border-right: none;
    border-bottom: 1px solid #e5e7eb;
  }
  
  .image-gallery {
    grid-template-columns: 1fr;
  }
}


/* 滚动条样式 */
.device-list-panel::-webkit-scrollbar,
.image-display-panel::-webkit-scrollbar {
  width: 6px;
}

.device-list-panel::-webkit-scrollbar-track,
.image-display-panel::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.device-list-panel::-webkit-scrollbar-thumb,
.image-display-panel::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.device-list-panel::-webkit-scrollbar-thumb:hover,
.image-display-panel::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 文件展示区域新样式 */
.file-display-panel {
  flex: 1;
  background: #ffffff;
  padding: 20px;
  overflow-y: auto;
}

.file-gallery {
  padding: 10px;
}

.file-card {
  background: #ffffff;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
}

.file-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.file-container {
  width: 100%;
  height: 200px;
  overflow: hidden;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

/* 坐标文件样式 */
.coordinate-container {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.coordinate-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
}

.coordinate-icon {
  font-size: 48px;
  margin-bottom: 12px;
  opacity: 0.9;
}

.coordinate-info {
  text-align: center;
}

.coordinate-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 4px;
}

.coordinate-desc {
  font-size: 12px;
  opacity: 0.8;
}

/* 文件覆盖层 */
.file-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.file-card:hover .file-overlay {
  opacity: 1;
}

.file-type-badge {
  background: rgba(255, 255, 255, 0.9);
  color: #333;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  margin-bottom: 8px;
}

.image-badge {
  background: rgba(103, 194, 58, 0.9);
  color: white;
}

.coordinate-badge {
  background: rgba(230, 162, 60, 0.9);
  color: white;
}

.file-action {
  color: white;
  font-size: 14px;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.file-caption {
  padding: 12px 16px;
  font-size: clamp(12px, 1vw, 16px);
  color: #374151;
  font-weight: 500;
  text-align: center;
  background: #ffffff;
  border-top: 1px solid #f3f4f6;
}

/* 文件预览对话框样式 */
:deep(.image-preview-dialog) {
  .el-message-box {
    max-width: 90vw;
    max-height: 90vh;
  }
}

:deep(.coordinate-file-dialog) {
  .el-message-box {
    max-width: 700px;
  }
}

/* 编辑模式样式 */
.edit-mode-buttons {
  display: flex;
  align-items: center;
  gap: 20px;
}

.edit-mode-title {
  font-size: 16px;
  font-weight: 600;
  color: #2196f3;
  padding: 8px 16px;
  background: #e3f2fd;
  border-radius: 4px;
}

.exit-btn:hover:not(:disabled) {
  background: #e8f5e8;
  border-color: #4caf50;
  color: #4caf50;
}

.import-btn:hover:not(:disabled) {
  background: #e3f2fd;
  border-color: #2196f3;
  color: #2196f3;
}

/* 图片编辑模式样式 */
.file-card.edit-mode {
  position: relative;
  border: 2px dashed #2196f3;
  background: #f8f9ff;
}

/* 可点击图片样式 */
.file-card.clickable {
  cursor: pointer;
  border: 2px solid #4caf50;
  background: #f0fff0;
  transition: all 0.3s ease;
}

.file-card.clickable:hover {
  border-color: #45a049;
  background: #e8f5e8;
  transform: translateY(-4px);
  box-shadow: 0 6px 20px rgba(76, 175, 80, 0.3);
}

.file-card.clickable .edit-overlay {
  background: rgba(76, 175, 80, 0.1);
}

.file-card.clickable .edit-info {
  background: rgba(76, 175, 80, 0.8);
  color: white;
}

.clickable-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(76, 175, 80, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.clickable-info {
  background: rgba(76, 175, 80, 0.8);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.delete-image-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: #f44336;
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  transition: all 0.2s ease;
}

.delete-image-btn:hover {
  background: #d32f2f;
  transform: scale(1.1);
}

.edit-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(33, 150, 243, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit-info {
  background: rgba(33, 150, 243, 0.8);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

/* 下载坐标文件按钮样式 */
.download-coordinate-btn {
  position: absolute;
  top: 8px;
  left: 8px;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: #2196f3;
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  transition: all 0.2s ease;
}

.download-coordinate-btn:hover {
  background: #1976d2;
  transform: scale(1.1);
}

/* 添加图片卡片样式 */
.add-image-card {
  border: 2px dashed #4caf50;
  background: #f8fff8;
  cursor: pointer;
  transition: all 0.3s ease;
}

.add-image-card:hover {
  border-color: #45a049;
  background: #f0fff0;
  transform: translateY(-2px);
}

.add-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #4caf50;
}

.add-icon {
  margin-bottom: 8px;
}

.add-text {
  font-size: 14px;
  font-weight: 500;
}

/* 文件夹样式 */
.folder-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start; /* 关键：让每个卡片独立控制高度，防止被同行其他卡片拉伸 */
  gap: 20px;
  margin-bottom: 24px;
}

.folder-section {
  flex: 0 0 280px; /* 固定宽度，不伸缩 */
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: #ffffff;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.folder-section:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.folder-header {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e5e7eb;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.folder-header:hover {
  background: #e9ecef;
}

.folder-icon {
  margin-right: 12px;
  color: #6c757d;
  font-size: 16px;
  transition: transform 0.2s ease;
}

.folder-icon.expanded {
  transform: rotate(90deg);
}

.folder-type-icon {
  margin-right: 12px;
  color: #ffc107;
  font-size: 20px;
}

.folder-name {
  font-size: 16px;
  font-weight: 600;
  color: #495057;
  flex: 1;
}

.folder-count {
  font-size: 14px;
  color: #6c757d;
  margin-left: 8px;
}

.folder-content {
  padding: 16px;
  background: #ffffff;
  border-top: 1px solid #f3f4f6;
}

.folder-images {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
}

.folder-images .file-card {
  margin: 0;
}

.folder-images .file-container {
  height: 100px;
}

.folder-images .file-caption {
  padding: 8px 12px;
  font-size: 12px;
}

/* 坐标文件单独显示区域 */
.coordinate-file-section {
  margin-top: 24px;
  display: flex;
  justify-content: flex-start;
}

.coordinate-file-section .file-card {
  width: 280px;
  max-width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .folder-container {
    gap: 16px;
  }
  
  .folder-section {
    flex: 0 0 240px; /* 移动端更小的宽度 */
  }
}

@media (max-width: 480px) {
  .folder-section {
    flex: 0 0 calc(100% - 20px); /* 小屏幕上占满宽度 */
  }
  
  .folder-header {
    padding: 12px 16px;
  }
  
  .folder-name {
    font-size: 14px;
  }
  
  .folder-count {
    font-size: 12px;
  }
  
  .folder-content {
    padding: 12px;
  }
  
  .folder-images {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 8px;
  }
  
  .folder-images .file-container {
    height: 80px;
  }
  
  .folder-images .file-caption {
    padding: 6px 8px;
    font-size: 11px;
  }
  
  .file-container {
    height: 160px;
  }
  
  .coordinate-icon {
    font-size: 36px;
  }
  
  .coordinate-title {
    font-size: 16px;
  }
  
  .edit-mode-buttons {
    flex-direction: column;
    gap: 10px;
  }
  
  .edit-mode-title {
    font-size: 14px;
    text-align: center;
  }
}

</style>
